package com.mi.common.security.util;

import com.mi.common.security.service.MiUser;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Security Utils
 *
 * @author jin_huaquan
 * @version 1.0
 * @date 2020/3/17 16:17
 */
public class SecurityUtils {

    public static MiUser getUserDetails() {
        MiUser userDetails;
        try {
            userDetails = (MiUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new AuthenticationServiceException("登录状态无效");
        }
        return userDetails;
    }

    /**
     * 获取当前登录用户的账号
     *
     * @return 登录用户账号(未登录则返回null)
     */
    public static String getUsername() {
        UserDetails userDetails;
        try {
            userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
        return userDetails.getUsername();
    }

    /**
     * 获取当前用户的用户ID
     *
     * @return 当前用户ID
     */
    public static Long getUserId() {
        return getUserDetails().getId();
    }
}
